package com.sugon.controller.module;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.sugon.annotation.AutoLog;
import com.sugon.annotation.NonBusinessParamValid;
import com.sugon.entity.FactoryTypeEntity;
import com.sugon.entity.ModuleSpEntity;
import com.sugon.entity.ModuleSpPurchasingBatchEntity;
import com.sugon.entity.dto.ModuleSpPurchasingBatchParam;
import com.sugon.modules.utils.DateUtil;
import com.sugon.service.FactoryTypeService;
import com.sugon.service.ModuleSpPurchasingBatchService;
import com.sugon.service.ModuleSpService;
import com.sugon.utils.PageUtils;
import com.sugon.utils.Query;
import com.sugon.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 模具型芯备件采购批次信息Controller
 *
 * @author sugon
 * @date 2021-10-13 09:58:53
 */
@Controller
@RequestMapping("modulesppurchasingbatch")
public class ModuleSpPurchasingBatchController {
    @Autowired
    private ModuleSpPurchasingBatchService moduleSpPurchasingBatchService;
    @Resource
    private FactoryTypeService factoryTypeService;
    @Resource
    private ModuleSpService moduleSpService;

    /**
     * 查看列表
     */
    @RequestMapping("/list")
    //@RequiresPermissions("modulesppurchasingbatch:list")
    @ResponseBody
    public R list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);

        List<ModuleSpPurchasingBatchEntity> moduleSpPurchasingBatchList = moduleSpPurchasingBatchService.queryList(query);
        int total = moduleSpPurchasingBatchService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(moduleSpPurchasingBatchList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }

    /**
     * 查看信息
     */
    @RequestMapping("/info/{id}")
    //@RequiresPermissions("modulesppurchasingbatch:info")
    @ResponseBody
    public R info(@PathVariable("id") String id) {
        ModuleSpPurchasingBatchEntity moduleSpPurchasingBatch = moduleSpPurchasingBatchService.queryObject(id);

        return R.ok().put("moduleSpPurchasingBatch", moduleSpPurchasingBatch);
    }

    /**
     * 保存
     */
    @NonBusinessParamValid
    @AutoLog("模具型芯备件采购批次信息--保存")
    @RequestMapping("/save")
    //@RequiresPermissions("modulesppurchasingbatch:save")
    @ResponseBody
    public R save(@Validated @RequestBody ModuleSpPurchasingBatchParam purchasingBatchParam, BindingResult bindingResult) {
        // 校验备件供应商是否存在
        FactoryTypeEntity factoryType = factoryTypeService.queryObject(purchasingBatchParam.getSupplierId());
        if (factoryType == null) {
            return R.error("模具型芯备件供应厂家不存在，请确认！");
        }
        if (StrUtil.isEmpty(factoryType.getSelfCode())) {
            return R.error("请完善完厂家代号后再进行该操作！");
        }
        // 校验模具型芯备件是否存在
        ModuleSpEntity moduleSp = moduleSpService.queryObject(purchasingBatchParam.getMoldSpId());
        if (moduleSp == null) {
            return R.error("模具型芯备件不存在，请确认！");
        }
        if (StrUtil.isEmpty(moduleSp.getUniqueBarCode())) {
            return R.error("请完善模具型芯备件条码代码后再进行该操作！");
        }
        // 校验单价不得小于0
        if (purchasingBatchParam.getUnitPrice().compareTo(BigDecimal.ZERO) < 0) {
            return R.error("采购单价不得小于0！");
        }
        // 结束月份不得小于起始月份
        if (purchasingBatchParam.getBeginMonth().compareTo(purchasingBatchParam.getEndMonth()) > 0) {
            return R.error("批次适用结束月份不得小于起始月份！");
        }
        ModuleSpPurchasingBatchEntity purchasingData = new ModuleSpPurchasingBatchEntity();
        CopyOptions copyOptions = CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true);
        BeanUtil.copyProperties(purchasingBatchParam, purchasingData, copyOptions);
        purchasingData.setBarCordAnalysisRule(StrUtil.format("{}{}({})", factoryType.getSelfCode(), moduleSp.getUniqueBarCode(), DateUtil.getMonthRangeStr(purchasingBatchParam.getBeginMonth(), purchasingBatchParam.getEndMonth())));
        boolean saveFlag = moduleSpPurchasingBatchService.save(purchasingData) > 0;
        if (saveFlag) {
            moduleSp.setLastPurchaseDate(purchasingData.getGmtCreate());
            moduleSpService.update(moduleSp);
        }
        return saveFlag ? R.ok() : R.error("添加失败，请稍后重试！");
    }

    /**
     * 修改
     */
    @NonBusinessParamValid
    @AutoLog("模具型芯备件采购批次信息--修改")
    @RequestMapping("/update")
    //@RequiresPermissions("modulesppurchasingbatch:update")
    @ResponseBody
    public R update(@Validated @RequestBody ModuleSpPurchasingBatchParam purchasingBatchParam, BindingResult bindingResult) {
        String id = purchasingBatchParam.getId();
        Assert.notBlank(id);
        ModuleSpPurchasingBatchEntity purchasingBatchInDB = moduleSpPurchasingBatchService.queryObject(id);
        if (purchasingBatchInDB == null) {
            return R.error("采购批次信息不存在，请确认！");
        }

        // 校验备件供应商是否存在
        FactoryTypeEntity factoryType = factoryTypeService.queryObject(purchasingBatchParam.getSupplierId());
        if (factoryType == null) {
            return R.error("模具型芯备件供应厂家不存在，请确认！");
        }
        if (StrUtil.isEmpty(factoryType.getSelfCode())) {
            return R.error("请完善完厂家代号后再进行该操作！");
        }
        // 校验模具型芯备件是否存在
        ModuleSpEntity moduleSp = moduleSpService.queryObject(purchasingBatchParam.getMoldSpId());
        if (moduleSp == null) {
            return R.error("模具型芯备件不存在，请确认！");
        }
        if (StrUtil.isEmpty(moduleSp.getUniqueBarCode())) {
            return R.error("请完善模具型芯备件条码代码后再进行该操作！");
        }
        // 校验单价不得小于0
        if (purchasingBatchParam.getUnitPrice().compareTo(BigDecimal.ZERO) < 0) {
            return R.error("采购单价不得小于0！");
        }
        // 结束月份不得小于起始月份
        if (purchasingBatchParam.getBeginMonth().compareTo(purchasingBatchParam.getEndMonth()) > 0) {
            return R.error("批次适用结束月份不得小于起始月份！");
        }
        CopyOptions copyOptions = CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true);
        BeanUtil.copyProperties(purchasingBatchParam, purchasingBatchInDB, copyOptions);
        purchasingBatchInDB.setBarCordAnalysisRule(StrUtil.format("{}{}({})", factoryType.getSelfCode(), moduleSp.getUniqueBarCode(), DateUtil.getMonthRangeStr(purchasingBatchParam.getBeginMonth(), purchasingBatchParam.getEndMonth())));
        return moduleSpPurchasingBatchService.save(purchasingBatchInDB) > 0 ? R.ok() : R.error("添加失败，请稍后重试！");
    }

    /**
     * 删除
     */
    @AutoLog("模具型芯备件采购批次信息--删除")
    @RequestMapping("/delete")
    //@RequiresPermissions("modulesppurchasingbatch:delete")
    @ResponseBody
    public R delete(@RequestBody String[] ids) {
        // 已产生出库或入库的记录不允许删除
        for (String id : ids) {
            ModuleSpPurchasingBatchEntity purchasingBatchData = moduleSpPurchasingBatchService.queryObject(id);
            Assert.isTrue(purchasingBatchData != null, "备件采购批次价格[{}]信息不存在，请确认！");
            if (purchasingBatchData.getStockInNum() > 0 || purchasingBatchData.getStockOutNum() > 0) {
                return R.error("已产生出入库的备件价格信息不允许删除！");
            }
        }
        // 执行批量删除
        moduleSpPurchasingBatchService.deleteBatch(ids);
        return R.ok();
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    @ResponseBody
    public R queryAll(@RequestParam Map<String, Object> params) {

        List<ModuleSpPurchasingBatchEntity> list = moduleSpPurchasingBatchService.queryList(params);

        return R.ok().put("list", list);
    }

    /**
     * 导入模具采购批次
     */
    @RequestMapping("/import")
    @ResponseBody
    public R importE(@RequestParam("file") MultipartFile file) throws Exception {
        if (file == null || file.isEmpty()) {
            return R.error("上传文件不能为空！");
        }
        int rows = moduleSpPurchasingBatchService.importMoldPurchaseBatchData(file.getInputStream());
        return R.ok("成功导入" + rows + "记录");
    }
}
